package com.beiing.tianshuai.tianshuai.activity;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Base64;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.app.AppConstant;
import com.beiing.tianshuai.tianshuai.base.BaseActivity;
import com.beiing.tianshuai.tianshuai.entity.UserInfoBean;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.beiing.tianshuai.tianshuai.util.NetBitmapUtils;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.open.utils.ThreadManager;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;

public class WebViewActivity extends BaseActivity {

    @BindView(R.id.wv_main_content)
    WebView mWvMainContent;
    @BindView(R.id.toolbar_iv_back)
    TextView mToolbarIvBack;
    @BindView(R.id.toolbar_iv_close)
    ImageView mToolbarIvClose;
    @BindView(R.id.toolbar_tv_title)
    TextView mToolbarTvTitle;
    @BindView(R.id.my_progress_bar)
    ProgressBar mMyProgressBar;

    private boolean isOnPause;
    private ValueCallback<Uri> mUploadMessage;
    public ValueCallback<Uri[]> uploadMessage;
    public static final int REQUEST_SELECT_FILE = 100;
    private final static int FILE_CHOOSER_RESULT_CODE = 2;
    private Dialog bottomDialog;
    private Context mContext;

    /**
     * 第三方分享
     */
    private Tencent mTencent;

    /**
     * 分享监听事件
     */
    private IUiListener mIUiListener = new IUiListener() {
        @Override
        public void onComplete(Object o) {
            showShortText("分享成功");
        }

        @Override
        public void onError(UiError uiError) {
            showShortText("分享失败");
        }

        @Override
        public void onCancel() {
            showShortText("取消分享");
        }
    };

    @Override
    protected int getLayoutId() {
        return R.layout.activity_web_view;
    }

    @Override
    protected void init() {
        mContext = this;
        mTencent = Tencent.createInstance("1106377834", mContext);
        ButterKnife.bind(this);
        Intent intent = getIntent();
        String url = intent.getStringExtra("url");
        String uid = UserInfoBean.getUid(this);
        String requestUrl = url + "?" +
                "token=9e304d4e8df1b74cfa009913198428ab" +
                "&uid=" +
                Base64.encodeToString(("app#" + uid).getBytes(), Base64.DEFAULT);
        initToolbar();
        initWebView(requestUrl);
    }

    private void initToolbar() {
        mToolbarIvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mWvMainContent.canGoBack()) {
                    mWvMainContent.goBack();
                } else {
                    finish();
                }
            }
        });
        mToolbarIvClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    @SuppressLint("AddJavascriptInterface")
    private void initWebView(String requestUrl) {
        WebSettings settings = mWvMainContent.getSettings();
        settings.setSupportZoom(true);
        settings.setJavaScriptEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        // 加快界面加载速度，等页面finish再加载图片
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            settings.setLoadsImagesAutomatically(true);
        } else {
            settings.setLoadsImagesAutomatically(false);
        }
        mWvMainContent.addJavascriptInterface(new onWebPageShareClick(), "control");
        mWvMainContent.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                if (!view.getSettings().getLoadsImagesAutomatically()) {
                    view.getSettings().setLoadsImagesAutomatically(true);
                }
            }
        });
        LogUtils.i(requestUrl, "URL");
        mWvMainContent.loadUrl(requestUrl);
        mWvMainContent.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                mToolbarTvTitle.setText(title == null ? "" : title);
            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    mMyProgressBar.setProgress(newProgress);
                    mMyProgressBar.setVisibility(View.GONE);
                } else {
                    mMyProgressBar.setProgress(newProgress);
                    mMyProgressBar.setVisibility(View.VISIBLE);
                }
                if (view.canGoBack()) {
                    mToolbarIvClose.setVisibility(View.VISIBLE);
                } else {
                    mToolbarIvClose.setVisibility(View.GONE);
                }
                super.onProgressChanged(view, newProgress);
            }

            // For 3.0+ Devices (Start)
            // onActivityResult attached before constructor
            protected void openFileChooser(ValueCallback uploadMsg, String acceptType) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                startActivityForResult(Intent.createChooser(i, "File Browser"), FILE_CHOOSER_RESULT_CODE);
            }

            // For Lollipop 5.0+ Devices
            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                if (uploadMessage != null) {
                    uploadMessage.onReceiveValue(null);
                    uploadMessage = null;
                }

                uploadMessage = filePathCallback;

                Intent intent = fileChooserParams.createIntent();
                try {
                    startActivityForResult(intent, REQUEST_SELECT_FILE);
                } catch (ActivityNotFoundException e) {
                    uploadMessage = null;
                    showLongText("Cannot Open File Chooser");
                    return false;
                }
                return true;
            }

            //For Android 4.1 only
            protected void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                mUploadMessage = uploadMsg;
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.setType("image/*");
                startActivityForResult(Intent.createChooser(intent, "File Browser"), FILE_CHOOSER_RESULT_CODE);
            }

            protected void openFileChooser(ValueCallback<Uri> uploadMsg) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                startActivityForResult(Intent.createChooser(i, "File Chooser"), FILE_CHOOSER_RESULT_CODE);
            }
        });
    }

    /**
     * 弹出分享提示框
     * @param url
     * @param cover
     * @param title
     * @param summary
     */
    private void showShareDialog(final String url, final String cover, final String title, final String summary) {
        bottomDialog = new Dialog(mContext, R.style.BottomDialog);
        @SuppressLint("InflateParams") View contentView = LayoutInflater.from(mContext).inflate(R.layout.dialog_interest_detail_bottom_share, null);
        RadioButton weChatFriends = contentView.findViewById(R.id.rb_wechat_friends);
        RadioButton weChatCircle = contentView.findViewById(R.id.rb_wechat_circle);
        RadioButton qqFriends = contentView.findViewById(R.id.rb_qq_friends);
        RadioButton qqZone = contentView.findViewById(R.id.rb_qzone);
        weChatFriends.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                shareToWeChatWithWebPage(mContext, url, title, summary, cover, 0);
                bottomDialog.dismiss();
            }
        });
        weChatCircle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                shareToWeChatWithWebPage(mContext, url, title, summary, cover, 1);
                bottomDialog.dismiss();
            }
        });
        qqFriends.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                shareToQQ(title, summary, url, cover);
                bottomDialog.dismiss();
            }
        });
        qqZone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                shareToQZone(title, summary, url, cover);
                bottomDialog.dismiss();
            }
        });

        bottomDialog.setContentView(contentView);
        ViewGroup.LayoutParams layoutParams = contentView.getLayoutParams();
        layoutParams.width = getResources().getDisplayMetrics().widthPixels;
        contentView.setLayoutParams(layoutParams);
        Window window = bottomDialog.getWindow();
        if (window != null) {
            window.setGravity(Gravity.BOTTOM);
            window.setWindowAnimations(R.style.BottomDialog_Animation);
        }
        bottomDialog.show();
        bottomDialog.setCanceledOnTouchOutside(true);
    }

    private void shareToWeChatWithWebPage(Context context, String url, String title, String description, final String cover, final int scene) {
        final IWXAPI iwxapi = WXAPIFactory.createWXAPI(context, AppConstant.WX_APP_ID);

        if (!iwxapi.isWXAppInstalled()) {
            showShortText("您尚未安装微信");
            return;
        }

        WXWebpageObject wxWebpageObject = new WXWebpageObject();
        wxWebpageObject.webpageUrl = url;
        final WXMediaMessage wxMediaMessage = new WXMediaMessage(wxWebpageObject);
        wxMediaMessage.mediaObject = wxWebpageObject;
        wxMediaMessage.title = title;
        wxMediaMessage.description = description;
        new Thread(new Runnable() {
            @Override
            public void run() {
                Bitmap thumb = NetBitmapUtils.getBitmap(cover);
                if (thumb != null) {
                    thumb = Bitmap.createScaledBitmap(thumb, 200, 200, true);
                }
                wxMediaMessage.setThumbImage(thumb);
                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = String.valueOf(System.currentTimeMillis());
                req.message = wxMediaMessage;
                req.scene = scene;

                iwxapi.sendReq(req);
            }
        }).start();
    }

    private void shareToQQ(String title, String summary, String url, String cover) {
        final Bundle params = new Bundle();
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
        params.putString(QQShare.SHARE_TO_QQ_TITLE, title);         //标题
        params.putString(QQShare.SHARE_TO_QQ_SUMMARY, summary);     //摘要
        params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, url);      //内容地址
        params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, cover);       //内容地址
        ThreadManager.getMainHandler().post(new Runnable() {
            @Override
            public void run() {
                mTencent.shareToQQ((WebViewActivity) mContext, params, mIUiListener);
            }
        });
    }

    private void shareToQZone(String title, String summary, String url, String cover) {
        final Bundle params = new Bundle();
        params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
        params.putString(QzoneShare.SHARE_TO_QQ_TITLE, title);         //标题
        params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, summary);     //摘要
        params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, url);      //内容地址
        params.putString(QzoneShare.SHARE_TO_QQ_IMAGE_URL, cover);      //内容地址
        params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, new ArrayList<String>());

        ThreadManager.getMainHandler().post(new Runnable() {
            @Override
            public void run() {
                mTencent.shareToQzone((WebViewActivity) mContext, params, mIUiListener);
            }
        });
    }

    /**
     * 拦截物理返回键，重新处理返回逻辑。
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        /*
         * webView.canGoBack()判断webView能否后退
         */
        if (keyCode == KeyEvent.KEYCODE_BACK && mWvMainContent.canGoBack()) {
            //webView后退
            mWvMainContent.goBack();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 当Activity执行onPause()时让WebView执行pause
     */
    @Override
    protected void onPause() {
        super.onPause();
        try {
            if (mWvMainContent != null) {
                mWvMainContent.getClass().getMethod("onPause").invoke(mWvMainContent, (Object[]) null);
                isOnPause = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 当Activity执行onResume()时让WebView执行resume
     */
    @Override
    protected void onResume() {
        super.onResume();
        try {
            if (isOnPause) {
                if (mWvMainContent != null) {
                    mWvMainContent.getClass().getMethod("onResume").invoke(mWvMainContent, (Object[]) null);
                }
                isOnPause = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        if (mWvMainContent != null) {
            mWvMainContent.getSettings().setBuiltInZoomControls(true);
            mWvMainContent.setVisibility(View.GONE);
            mWvMainContent.destroy();
            mWvMainContent = null;
        }
        isOnPause = false;
        super.onDestroy();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            if (requestCode == REQUEST_SELECT_FILE) {
                if (uploadMessage == null)
                    return;
                uploadMessage.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, intent));
                uploadMessage = null;
            }
        } else if (requestCode == FILE_CHOOSER_RESULT_CODE) {
            if (null == mUploadMessage)
                return;
            // Use MainActivity.RESULT_OK if you're implementing WebView inside Fragment
            // Use RESULT_OK only if you're implementing WebView inside an Activity
            Uri result = intent == null || resultCode != MainActivity.RESULT_OK ? null : intent.getData();
            mUploadMessage.onReceiveValue(result);
            mUploadMessage = null;
        } else {
            showLongText("Failed to Upload Image");
        }
    }

    private class onWebPageShareClick {

        @JavascriptInterface
        public void onWebPageShareClick(String cover, String url, String title, String summary) {
            LogUtils.i(cover, "cover");
            LogUtils.i(url, "url");
            LogUtils.i(title, "title");
            LogUtils.i(summary, "summary");
            showShareDialog(url, cover, title, summary);
        }
    }
}
